package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import admin.forms.ApplicationForm;
import admin.models.ApplicationModel;

import entities.Application;

public class ApplicationAddServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		
		Application app = new Application();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("app", app);
		try {
			request.getRequestDispatcher("/admin/pages/application_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationModel appModel = ApplicationModel.getInstance();
		Application app = new Application();
		
		TreeMap form = (TreeMap) ApplicationForm.checkValid(request, app);
		app = (Application) form.get("app");
		TreeMap check = (TreeMap) form.get("checkValid");
		
		if (check.size() == 0) {
			appModel.insert(app);
			request.setAttribute("success", "Add success application " + app.getId());
			app = new Application();
		}
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("app", app);
		try {
			request.getRequestDispatcher("/admin/pages/application_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
